import {
    AfterViewInit,
    Component,
    ElementRef,
    EventEmitter,
    OnDestroy,
    OnInit,
    Output,
    Renderer2,
    ViewChild
} from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { Subject } from 'rxjs';
import { ValidatorService } from '../../../../../common/validator.service';
import { DragDrop } from '@angular/cdk/drag-drop';
import { AssignUserService } from '../../service/assign-user.service';

@Component({
    selector: 'app-assign-user-option',
    templateUrl: './index.html',
    styleUrls: ['./index.scss'],
})
export class AssignUserOptionComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('modalContent') modalContent: any;
    @ViewChild('modalFooter') modalFooter: any;
    @Output() getMainList: EventEmitter<any> = new EventEmitter<any>();
    modalLoadingState: boolean;
    saveLoadingState: boolean;
    onDestroy$: Subject<any> = new Subject<any>();
    modalRef: NzModalRef; //用户操作弹窗
    users: any[] = [];
    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private router: Router,
        private _nzModalService: NzModalService,
        private _validService: ValidatorService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private mainService: AssignUserService
    ) {
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
        this.onDestroy$.complete();
    }


    /**
     * 操作弹窗
     */
    onModalOpen(roleId: string) {
        this.modalRef = this._nzModalService.create({
            nzTitle: '选择用户',
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: this._config.modalWidth,
            nzBodyStyle: this._config.modalContentHeight,
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            this.resetSearchObject();
        });

        if (roleId) {
            this.searchObj.roleId = roleId;
            this.getUnallocatedList();
        }
    }

    getUnallocatedList(){
        this.modalLoadingState = true;
        this.mainService.unallocatedList(this.searchObj).subscribe((res) => {
            if (res.success) {
                this.users = res.rows;
                this.total = res.total;
            }
        }).add(() => this.modalLoadingState = false);
    }



    @ViewChild('rowSelectionTable') rowSelectionTable: ElementRef;
    checked = false;
    loading = false;
    indeterminate = false;
    setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.refreshStatus();
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
  }

      onAllChecked(checked: boolean): void {
        this.users.forEach(item => this.updateCheckedSet(item.userId, checked));
      }

      refreshStatus() {
          if (this.setOfCheckedId.size == 0){
              this.indeterminate = false;
              this.checked = false;
          }
          else if (this.setOfCheckedId.size == this.users.length){
              this.indeterminate = false;
              this.checked = true;
          }
          else if (this.setOfCheckedId.size > 0){
              this.indeterminate = true;
          }
      }

    sendRequest(): void {
      this.loading = true;
      console.log(this.setOfCheckedId);
      const data = {
          roleId: this.searchObj.roleId,
          userIds: Array.from(this.setOfCheckedId).join(',')
      };
      this.mainService.selectAll(data).subscribe(res => {}).add(() => (this.loading = false));
  }

    searchObj:any = {
        pageNum: 1,
        pageSize: this._config.pageSize,
        userName: '',
        phonenumber: '',
    };
    total: any;

    searchList() {
        this.getUnallocatedList()
    }

    keyEnter($event: KeyboardEvent) {
        if($event.key === 'Enter'){
            this.searchList();
        }
    }

    resetSearchObject(){
        this.searchObj = {
            roleId:this.searchObj.roleId,
            pageNum: 1,
            pageSize: this._config.pageSize,
        };
    }

}
